<?php

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Db;
use think\Cache;
use think\Config;
// use think\Validate;//验证
// use fast\Random;
// use fast\Http;

// use app\api\controller\Xiaohe;


/**
 * 我的(小程序授权)📲
 */
class Me extends Api
{
    // protected $noNeedLogin = ['*'];
    protected $noNeedLogin = ['get_openid','get_user_mobile','getinit','get_hot_qrcode'];
    protected $noNeedRight = ['*'];

    // protected $stores = null;




    // public $uid = '';
    public function _initialize()
    {
        parent::_initialize();
     
        // $uid = $this->request->param('uid');//用户uid 需要解密
        // if(!empty($uid))$this->auth->id_de($uid);
        // $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    /**
     * 获取openid
     * @ApiSummary (里面有token，提交接口都要带上)
     * @param [type] $code
     * @return void
     */
    public function get_openid($code=null){
    
        $app = $this->get_app();
        $user = $app->auth->session($code);
        if(!empty($user['errcode'])){
            halt($user);
        }
        $openid = $user['openid'];
     
        $data = array();
        $data['openid'] = $openid;
        $user_data = Db::name('user')->where('openid',$openid)->find();
        if($user_data){
            $ret = $this->auth->direct($user_data['id']);
            $data = $this->auth->getUserinfo();
            // $data['uid'] = $user_data['id'];


            // $data['logintime'] = time();
            //开放平台
            if(empty($user_data['unionid']) && (!empty($user['unionid']))){
                Db::name('user')->where('openid',$openid)->update(['unionid'=>$user['unionid']]);
            }
        }else{

            $indata['openid'] = $openid;
            $indata['createtime'] = time();
            $indata['jointime'] = $indata['createtime'];
            $indata['joinip'] = $this->request->ip();
            $indata['logintime'] = time();
            $indata['status'] = 'normal';

            // $indata['stateswitch'] = 1;

            //开放平台
            if(!empty($user['unionid'])){
                $indata['unionid'] = $user['unionid'];
            }
            
     
            $id = Db::name('user')->insertGetId($indata);
            $ret = $this->auth->direct($id);

            $data = $this->auth->getUserinfo();
        }
        
        // $data['is']     = $data['uid'];//未知
        return json($data);
    }



    /**
     * 修改小程序用户的昵称和头像
     *
     * @param string $nickname 昵称
     * @param string $img 头像
     * @return void
     */ 
    public function che_user($nickname,$img)
    {   
        
        $u['id'] = $this->auth->id;
        $json['code'] = -1;
        $json['msg'] = '修改失败';

        $data['nickname'] = $nickname;
        $data['avatar'] = $img;
        $res = Db::name('user')->where($u)->update($data);
        if($res){
            $json['code'] = 1;
            $json['msg'] = '修改成功';
        }
        return json($json);
    }


    /**
     * 获取用户信息
     *
     * @return void
     */
    public function get_user()
    {
        

        $list['user'] = Db::name('user')->find($this->auth->id);
        // $list['user']['play_min'] = ceil($this->get_user_paly_time($this->auth->id)/60);
        // $list['space'] = Db::name('space')->where('uid',$this->auth->id)->find();
        // $list['user']['vip_stime'] = date('Y-m-d',$list['user']['vip_stime']);
        // $list['user']['vip_etime'] = date('Y-m-d',$list['user']['vip_etime']);


        return json($list);
    }



    /**
     * 修改上级
     *
     * @param string $pid 用户id
     * @return void
     */
    public function update_pid($pid)
    {
        
        $user = Db::name('user')->find($this->auth->id);
        if($user){
            if(!empty($user['pid'])){
                $this->error('已经有上级'.$user['pid']);
            }
        }

        
        $res_up = Db::name('user')->where('id',$this->auth->id)->update(['pid'=>$pid]);
        if($res_up){
            $this->success('绑定成功');
        }
    } 
    


    /**
     * 小程序授权获取手机号
     *
     * @param string $code
     * @return void
     */    
    public function get_user_mobile($code=null)
    {   
        $app = $this->get_app();
        $data = $this->request->param();
        $user = $app->auth->session($code);
        $iv = $data['iv'];
        $encryptedData = $data['encryptedData'];

        $session = $user['session_key'];//$app->sns->getSessionKey($code);
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptedData);

        //修改手机号
        Db::name('user')->where('openid',$user['openid'])->update(['mobile'=>$decryptedData['phoneNumber']]);
        
        return $decryptedData['phoneNumber'];
        // halt($decryptedData);
        
    }

    /**
     * 获取活动🎡小程序二维码
     *
     * @return void
     */
    public function get_hot_qrcode()
    {
       $this->success('ok','/'.$this->get_hot_qrcode_self());
    }

    /**
     * 获取活动🎡小程序二维码
     *
     * @return void
     */
    protected function get_hot_qrcode_self()
    {
        $uid = 999999;
        $data['uid'] = $this->auth->id?$this->auth->id:$uid;
        // $data['order'] = $order;
        $data['time'] = time();
        $data['type'] = '2';//
        

        $path=Config::get('site.qr_pages')."?".http_build_query($data);
        
        $file_path = 'assets/appqr/';
            if (!is_dir($file_path)) {
                mkdir($file_path, 0755, true);
            }
        $app = $this->get_app();
        $response = $app->app_code->get($path, [
            'width' => 98,
            'line_color' => [
                'r' => 0,
                'g' => 0,
                'b' => 0,
            ],
        ]);
        $p  = $file_path.$data['uid'].'.png';
        if(is_file($p)){
            unlink($p);
        }
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save($file_path,$data['uid'].'.png');
            // halt($filename);
            return $file_path.$filename;
        }
    }

    /**
     * 获取配置
     *
     * @return void
     */
    public function getinit()
    {

        $key = 'haibao_all';
        $images = Cache::get($key);
        if(!$images){
            Cache::set($key,Db::name('image')->select(),60);
            // Cache::set($key,Db::name('image')->where('date',date('Y_m_d'))->value('image'));
            $images = Cache::get($key);
        }

        $key = 'image_index';
        $bj = Cache::get($key);
        if(!$bj){
            Cache::set($key,Db::name('image_index')->where('date',date('Y_m_d'))->value('image'),60);
            $bj = Cache::get($key);
        }
        $this->success('ok',['con'=>Config::get('site.api_debug'),'images'=>$images,'bj'=>$bj]);
    }



    // /**
    //  * 获取我的邀请人数
    //  *
    //  * @param boolean $self 掉接口不需要传
    //  * @return void
    //  */
    // public function user_get_my_share_num($self=false)
    // {
        
    //     $num = Db::name('user')
    //                 ->where('pid',$this->auth->id)
    //                 ->count();
    //     if($self){
    //         return $num; 
    //     }
    //     $this->success('👌',$num);
        

    // }







    // /**
    //  * 获取我的包场分享二维码💮
    //  *
    //  * @param string $order 订单
    //  * @return void
    //  */
    // public function get_baochang_qr($order)
    // {
    //    $Qrcode = new \app\api\controller\Qrcode();
    //    $url = $Qrcode->get_share_baochang_qrcode($order);
    //    if($url){
    //        $this->success('ok','/'.$url);
    //    }
    // }


  






    // /**
    //  * 获取到场出门二维码💮
    //  *
    //  * @param string $order 订单
    //  * @return void
    //  */
    // public function get_daochang_out_door_qr($order)
    // {
    //     $order_data = Db::name('order')->where('order',$order)->find();
    //     if($order_data['uid']!=$this->auth->id){
    //         $this->error('非本人订单');
    //     }
    //     if($order_data['pay_status']!='2'){
    //         $this->error('非支付状态');
    //     }

    //     $Qrcode = new \app\api\controller\Qrcode();
    //     $qr = $Qrcode->get_out_door_qrcode($order,true);
    //     $this->success('到场出门',$qr);
    // }

    /**
     * 获取小程序
     * @ApiWeigh (998)
     * @ApiInternal()
     * @return void
     */
    protected function get_app(){
        $config = [
            'app_id' => Config('site.app_id'),
            'secret' => Config('site.secret'),
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'driver' => 'daily',
               // 'level' => 'debug', //info  'driver' => 'daily', 
                // 'file' => __DIR__.'/wechat.log',
            ],
        ];

        $app = Factory::miniProgram($config);
        return $app;
    }


    /**
     * 获取微信公众号
     * @ApiWeigh (997)
     * @ApiInternal()
     * @return void
     */
    protected function get_wx_gzh_app()
    {
         $config = [
             'app_id' => Config('site.wx_app_id'),//,
             'secret' => Config('site.wx_secret'),//,
         
             // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
             'response_type' => 'array',
         
             //...
         ];
         
         $app = Factory::officialAccount($config);

         return $app;
    }

}